<script setup lang="ts">
// /api/admin/profits/service-types/stats
import { useECharts } from "@pureadmin/utils";
import { ref, watch, nextTick, PropType } from "vue";
import { useDark } from "@pureadmin/utils";
import { generatePalette } from "@/plugins/echarts";

// TS 类型定义
interface TimeStat {
  period: string;
  cost: number;
  profit: number;
  sales: number;
  tasks: number;
}
interface ServiceProfitItem {
  serviceType: string;
  totalProfit: number;
  timeStats: TimeStat[];
  totalSales: number;
  totalTasks: number;
  totalCost: number;
}

// 组件 prop：直接传入一个数组，每个元素为 ServiceProfitItem
const props = defineProps({
  data: {
    type: Array as PropType<ServiceProfitItem[]>,
    default: () => []
  }
});

// 初始化
const chartRef = ref<HTMLDivElement>();
const { isDark } = useDark();
const themeName = "lowSaturationFancy";
const { setOptions } = useECharts(chartRef, { theme: themeName });

// 监听数据变化
watch(
  () => props.data,
  async list => {
    await nextTick();

    // 构造饼图数据
    const seriesData = list.map(item => ({
      value: item.totalProfit,
      name: item.serviceType
    }));
    // 动态配色，色板长度 = 数据长度
    const colors = generatePalette(seriesData.length);

    setOptions({
      color: colors,
      tooltip: {
        trigger: "item",
        formatter: "{b}: {c} ({d}%)"
      },
      legend: {
        orient: "vertical",
        left: "left",
        bottom: "10%",
        textStyle: { color: isDark.value ? "#fff" : "#666", fontSize: 12 }
      },
      series: [
        {
          name: "服务类型收益",
          type: "pie",
          radius: ["40%", "70%"],
          center: ["60%", "50%"],
          data: seriesData,
          label: {
            show: true,
            position: "outside",
            formatter: "{b}: {d}%",
            fontSize: 12
          },
          labelLine: { smooth: true, length: 12, length2: 8 },
          emphasis: {
            itemStyle: { shadowBlur: 10, shadowColor: "rgba(0,0,0,0.5)" }
          }
        }
      ]
    });
  },
  { immediate: true }
);
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 365px" />
</template>
